package com.atguigu.kaiser;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @program: IDEAcode
 * @description:DES加密数据与解密
 * @author: Mr.zjx
 * create: 2021-08-04-16-08
 **/
public class DesDemo {
    public static void main(String[] args) throws Exception {
        String input = "尚硅谷";
        String key = "12345678";//des加密必须是八位
        String transformation = "DES";
        String algorithm = "DES";
        String encryptDES = encryptDES(input, key, transformation, algorithm);
        System.out.println("加密:" + encryptDES);
        String s = decryptDES(encryptDES, key, transformation, algorithm);
        System.out.println("解密:" + s);
    }

    //DES加密数据
    private static String encryptDES(String input,String key,String transformation,String algorithm) throws Exception{
        //getInstance获取加密对象：已封装好，静态调用返回本类对象
        Cipher cipher = Cipher.getInstance(transformation);
        //第一个参数：key的字节，第二个参数：加密算法
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        //初始化加密模式和算法
        cipher.init(Cipher.ENCRYPT_MODE,sks);
        //加密
        byte[] bytes = cipher.doFinal(input.getBytes());
        //输出加密后的数据
        String encode = Base64.encode(bytes);
        return encode;
    }

    //DES解密
    private static String decryptDES(String input,String key,String transformation,String algorithm) throws Exception{
        Cipher cipher = Cipher.getInstance(transformation);
        //获取Cipher对象
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        cipher.init(Cipher.DECRYPT_MODE,sks);
        //解密
        byte[] bytes = cipher.doFinal(Base64.decode(input));
        return new String(bytes);
    }
}
